<template>
  <section>
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入用户名" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search" icon="el-icon-search">查询</el-button>
        </el-form-item>

        <el-form-item style="float: right">
          <el-button type="primary" @click="showAddOrUpdate(null)" icon="el-icon-plus">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-table :data="dataList" border highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%">
      <el-table-column header-align="center" align="center" type="selection" width="55"></el-table-column>
      <el-table-column header-align="center" align="center" type="index" width="50"></el-table-column>
      <el-table-column header-align="center" prop="username" label="用户名" min-width="120"></el-table-column>
      <el-table-column header-align="center" prop="realName" label="真实姓名" min-width="120"></el-table-column>
      <el-table-column header-align="center" prop="mobilePhone" label="手机号" min-width="120"></el-table-column>
      <el-table-column header-align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit" @click="showAddOrUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="Delete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length==0">批量删除</el-button>
      <el-button type="success" @click="batchAuthorize" :disabled="this.sels.length==0">批量授权</el-button>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :page-sizes="pageSizes"
                     :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <el-dialog :title="formTitle" :visible.sync="visible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="80px" :rules="formRules">
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="dataForm.username"  ></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="dataForm.realName"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="dataForm.password"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobilePhone">
          <el-input v-model="dataForm.mobilePhone"/>
        </el-form-item>
        <el-form-item label="用户类别" prop="userType">
          <el-radio-group v-model="dataForm.userType">
            <el-radio :label="1" border>管理员</el-radio>
            <el-radio :label="2" border>普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="visible=false">取消</el-button>
        <el-button type="primary" @click.native="submit" :loading="submitLoading">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="授权" :visible.sync="authorizeVisible" :close-on-click-modal="false">
      <el-table :data="roleList" border highlight-current-row @selection-change="roleSelsChange" max-height="500">
        <el-table-column header-align="center" align="center" type="selection" width="50"></el-table-column>
        <el-table-column header-align="center" align="center" type="index" width="50"></el-table-column>
        <el-table-column header-align="center" align="center" prop="roleName" label="角色名称" min-width="80"></el-table-column>
        <el-table-column header-align="center" align="center" prop="available" label="可用性" min-width="80"
                         :filters="[{text:'可用',value:1},{text:'禁用',value:-1}]"
                         :filter-method="filterAvailable" filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.available===1">可用</el-tag>
            <el-tag type="danger" v-else-if="scope.row.available===-1">禁用</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="authorizeVisible=false">取消</el-button>
        <el-button type="primary" @click.native="submitRoles" :loading="submitLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
  import API from '@/api'
  export default {
    name: "index",
    data(){
      return{
        action:'',
        filters:{
          keyword:''
        },
        value:"",
        checkrolaname:false,
        checkrealName:false,
        checkpassword:false,
        checkmobliePhone:false,
        checkuserType:"",
        userdisabled:false,
        listLoading:false,
        dataList:[],
        checkvisible:false,
        total: 0,
        pageIndex: 1, //页码
        pageSize: this.CONSTANT.PAGE_SIZE, //分页大小
        pageSizes: this.CONSTANT.PAGE_SIZES, //分页大小选择列表

        sels:[],  //选中的数据数组

        //表单
        formAction:"",  //add-新增，edit-编辑
        formTitle:"", //表单标题
        visible:false,  //可见性
        submitLoading:false,  //提交等待
        dataForm:{},
        dataFormInit:{
          id:"",
          username:"",
          password:"",
          realName:"",
          mobilePhone:"",
          userType: 2
        },
        formRules:{
          username:[
            {
              required:true, message:"请输入用户名", trigger:'blur'
            },
            {min: 4, max: 15, message: '长度为4-15个字符', trigger: 'blur'}
          ],
          realName:[{required:true, message:"请输入真实姓名", trigger:'blur'}],
          password:[
            {required:true,message:"请输入密码",trigger:'blur'},
            {min: 6, max: 18, message: '长度为6-18个字符', trigger: 'blur'}
          ],
          mobilePhone:[{validator:(rule,value,callback)=>{

              let reg=/^1[3|4|5|8][0-9]\d{4,8}$/;

              if(reg.test(value) == false&&value){
                callback(new Error("手机号格式不正确"));
              }
            }, trigger:'blur',required:true,message:'请输入手机号'}],
          userType:[
            {required:true,message:"请选择用户类别",trigger:'blur'}
          ]
        },

        //授权表单
        authorizeVisible:false,
        roleList:[],
        roleSels:[]
      }
    },
    methods:{
      search(){
        this.getUserList();
      },
      showAddOrUpdate(data){
        this.dataForm = data?data:Object.assign({},this.dataFormInit);
        this.formAction = data?"edit":"add";
        this.formTitle = this.formAction==='add'?"新增":"编辑";
        this.visible = true;
        if(data==null)
        {this.userdisabled=false;}
        else{this.userdisabled=true;}
      },
      Delete(data){
        console.log(data.id);
        this.$confirm('此操作将永久删除这些配置信息，是否继续','警告',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning'
        }).then(()=>{
          this.idList = data.id.toString().split(",");
          console.log(this.idList);
          API.user.remove(this.idList).then((res)=>{
            console.log(res.data.code);
            if(!res.data.code){
              this.$message({
                message:"删除成功",
                type:"success"
              });
              this.getUserList();
            }else{
              this.$message.error(res.data.msg);
            }
          }).catch(error=>{
            console.error(error);
          })
        })
      },
      submit(){
        this.submitLoading = true;
        console.log(this.dataForm);
        let tick = this.formAction === 'add' ? API.user.add(this.dataForm):API.user.modify(this.dataForm);
        tick.then((res)=>{
          console.log(res.data);
          if(!res.data.code){
            this.$message({
              message:"操作成功",
              type:"success"
            });
            this.getUserList();
            this.visible = false;
          }else {
            this.$message({type:'error',dangerouslyUseHTMLString: true,message:res.data.msg,center:true});
          }
          this.submitLoading = false;
        }).catch((error)=>{
          this.$message({type:'error',dangerouslyUseHTMLString: true,message:res.data.msg,center:true});
        });
      },
      submitRoles(){
        this.submitLoading = true;
        let params = {
          userIdList:this.sels.map(item=>item.id).toString().split(","),
          roleIdList:this.roleSels.map(item=>item.id).toString().split(",")
        };
        API.user.modifyBatch(params).then((res)=>{
          if(!res.data.code){
            this.$message({
              message:"操作成功",
              type:"success"
            });
            this.authorizeVisible = false;
          }else {
            this.$message.error(res.data.msg);
          }
          this.submitLoading = false;
        }).catch(error=>{
          console.error(error);
          this.submitLoading = false;
        })
      },
      getUserList(){
        this.userdisabled=false;
        this.listLoading = true;
          let params = {
            limit:this.pageSize,
            page:this.pageIndex,
            keyword:this.filters.keyword
          };
          API.user.list(params).then(res=>{
            console.log(params);
            console.log(res.data.page);
            if(!res.data.code){
              this.dataList = res.data.page.list;
              this.total = res.data.page.totalCount;
            }else {
              this.$message.error(res.data.msg);
            }
            this.listLoading = false;
          }).catch(error=>{
            console.log(error);
            this.$message.error(error);
            this.listLoading = false;
          });
      },
      selsChange(sels){
        this.sels = sels;
      },
      roleSelsChange(sels){
        this.roleSels = sels;
      },
      batchRemove() {
        this.$confirm('此操作将永久删除这些配置信息，是否继续','警告',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning'
        }).then(()=>{
          this.idList = this.sels.map(item=>item.id).toString().split(",");
          console.log(this.idList);
          API.user.remove(this.idList).then((res)=>{
            console.log(res.data.code);
            if(!res.data.code){
              this.$message({
                message:"删除成功",
                type:"success"
              });
              this.getUserList();
            }else{
              this.$message.error(res.data.msg);
            }
          }).catch(error=>{
            console.error(error);
          })
        })
      },
      batchAuthorize(){
        API.role.select().then(res=>{
          console.log(res.data);
          this.roleList = res.data.list;
          this.authorizeVisible = true;
        }).catch(error=>{
          console.error(error);
        });
      },
      filterAvailable(value,row){
        return row.available === value;
      },
      handleSizeChange(value){
        this.pageSize = value;
        this.getUserList();
      },
      handleCurrentChange(value){
        this.pageIndex = value;
        this.getUserList();
      }
    },
    mounted(){
      this.getUserList();
    }
  }
</script>
